package com.example.jasypt.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.example.jasypt.http.Response;
import com.example.jasypt.service.EncryptorService;
import org.jasypt.encryption.StringEncryptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *
 * </p>
 *
 * @author 王令
 * @since 2022/9/2 20:41
 */
@RestController
@RequestMapping("/jasypt")
public class JasyptController {

    @Autowired
    private EncryptorService service;

    @GetMapping("/random-secret")
    public Response<String> randomSecret() {
        return Response.setData(RandomUtil.randomString(20));
    }

    @PostMapping("/encrypt/{secret}")
    public Response<List<String>> encrypt(@PathVariable("secret") String secret, @RequestBody List<String> raws) {
        StringEncryptor encryptor = service.stringEncryptor(secret);
        List<String> encoded = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(raws)) {
            for (String raw : raws) {
                encoded.add(encryptor.encrypt(raw));
            }
        }
        return Response.ok(encoded);
    }
}
